package com.atguigu.jxc.controller;

import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.service.CustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author huangxin
 * @description
 * @date 2020/12/2
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    // 客户列表分页（名称模糊查询）
    // http://localhost:8080/customer/list
    @PostMapping("/list")
    public Map<String, Object> getCustomersByPageAndCondition(Integer page, Integer rows, String customerName) {
        // 开启分页功能
        // 注意参数传递：将数据通过ThreadLocal绑定到当前线程上，传递给后续流程（dao）使用
        PageHelper.startPage(page, rows);
        PageInfo<Customer> pageInfo = customerService.getCustomersByPageAndCondition(customerName);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("rows", pageInfo.getList());
        return resultMap;
    }

    // 客户添加或修改
    // http://localhost:8080/customer/save?customerId=1
    @PostMapping("/save")
    @SuppressWarnings("rawtypes")
    public ServiceVO saveOrUpdateCustomer(Integer customerId, Customer customer) {
        if (Objects.isNull(customerId)) {
            customerService.saveCustomer(customer);
        } else {
            customer.setCustomerId(customerId);
            customerService.updateCustomerById(customer);
        }
        return new ServiceVO(100, "请求成功");
    }

    // 客户删除（支持批量删除）
    // http://localhost:8080/customer/delete
    // ids: 4,6,7
    @PostMapping("/delete")
    @SuppressWarnings("rawtypes")
    public ServiceVO deleteCustomersBatch(String ids) {
        customerService.deleteCustomersBatch(ids);
        return new ServiceVO(100, "请求成功");
    }

    // 获取客户列表
    // http://localhost:8080/customer/getComboboxList
    @PostMapping("/getComboboxList")
    public List<Map<String, Object>> getAllCustomers() {
        return customerService.getAllCustomers();
    }
}
